package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.anno.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.DestroyFailedException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class DishServiceimpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetMealDishMapper setMealDishMapper;
    @Override
    @AutoFill(value = OperationType.INSERT)
    @Transactional(rollbackFor = Exception.class)
    public void save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dishMapper.insert(dish);
        //获取当前插入的菜品的id
        for (DishFlavor flavor : dishDTO.getFlavors()) {
            flavor.setDishId(dish.getId());
            //插入
            dishFlavorMapper.insert(flavor);
        }
    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage()
                           ,dishPageQueryDTO.getPageSize());
        Page<DishVO> dishVOS = (Page<DishVO>) dishMapper.pageQuery(dishPageQueryDTO);

        return new PageResult(dishVOS.getTotal(), dishVOS.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Long> ids) {
        log.info("批量删除菜品：{}", ids);
        //判断菜品是否在售
        for (Long id : ids) {
            DishVO dish = dishMapper.getById(id);
            if (dish.getStatus() == 1) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断菜品是否关联了套餐
       List<SetmealDish> setmealDish = setMealDishMapper.QueryByDishId(ids);
        if (setmealDish != null) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品
        dishMapper.deleteByIds(ids);
        //TODO XML找不到ID 有错误 不能删除 待修复  已修复
        //删除菜品的口味数据
        dishFlavorMapper.deleteByDishId(ids);

    }

    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        log.info("查询菜品：{}", id);
        //查询菜品数据
        DishVO dishVO = dishMapper.getById(id);
        //查询菜品口味数据
        List<DishFlavor> dishFlavor =  dishFlavorMapper.getByDishId(id);
        //设置菜品口味数据
        dishVO.setFlavors(dishFlavor);

        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Override
    public void update(DishDTO dishDTO) {
        log.info("修改菜品：{}", dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品数据
        dishMapper.update(dish);
        //删除菜品口味数据
        dishFlavorMapper.deleteByDishId(Arrays.asList(dish.getId()));
        //重新插入菜品口味数据
        for (DishFlavor flavor : dishDTO.getFlavors()) {
            flavor.setDishId(dish.getId());
            dishFlavorMapper.insert(flavor);
        }



    }

    /**
     * 起售停售
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        log.info("起售、停售：{}", status);
        //如果菜品关联了套餐，则不能禁用
        List<SetmealDish> setmealDish = setMealDishMapper.QueryByDishId(Arrays.asList(id));
        if (setmealDish != null) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
                dishMapper.update(dish);
    }



    @Override
    public List<DishVO> list(String categoryId) {
        log.info("查询菜品：{}", categoryId);
        List<DishVO> list = dishMapper.list(categoryId);
        return list;
    }


    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.listbyDish(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
